﻿Imports System.Web
Imports System.Web.Configuration
Imports System.IO
Imports System.Net

Friend Class Helpers

    Friend Shared Function GetHexColor(ByVal c As System.Drawing.Color) As String
        Return String.Concat("#", c.R.ToString("X2", Nothing), c.G.ToString("X2", Nothing), c.B.ToString("X2", Nothing))
    End Function

    Friend Shared Function IsValidWebImage(ByVal path As String) As Boolean
        Dim imgFormats As String() = New String() {".jpg", ".jpeg", ".png", ".gif"}
        For Each f As String In imgFormats
            If IO.Path.GetExtension(path) = f Then
                Return True
            End If
        Next
        Return False
    End Function

    Friend Shared Function GetImageCodecInfo(ByVal mimeType As String) As ImageCodecInfo
        Dim i As Integer = 0
        Dim encoders As ImageCodecInfo()
        encoders = ImageCodecInfo.GetImageEncoders()
        Do While i < encoders.Length
            If encoders(i).MimeType = mimeType.Trim.Replace("pjpeg", "jpeg") Then
                Return encoders(i)
            End If
            i += 1
        Loop
        Return Nothing
    End Function

    Friend Shared Function GetImageMimeType(ByVal imagePath As String) As String
        Dim ext As String = IO.Path.GetExtension(imagePath)
        Dim mime As String = String.Empty
        Select Case ext.ToLower
            Case ".jpg", ".jpeg"
                mime = "image/jpeg"
            Case ".gif"
                mime = "image/gif"
            Case ".png"
                mime = "image/png"
            Case Else
                mime = "image/jpeg"
        End Select
        Return mime
    End Function

    Friend Shared Function GetVirtualFromRelativePath(ByVal relativePath As String) As String
        Dim path1 As String = HttpContext.Current.Server.MapPath("~")
        Dim path2 As String = HttpContext.Current.Server.MapPath(relativePath)
        Dim path As String = String.Format("~{0}", path2.Substring(path1.Length - 1))

        path = path.Replace("\", "/")

        Return path
    End Function

    Friend Shared Function GetHandlerPath(ByVal handlerType As Type) As String
        Dim hadlerPath As String = String.Empty
        Dim handlerSection As System.Web.Configuration.HttpHandlersSection = TryCast(WebConfigurationManager.GetWebApplicationSection("system.web/httpHandlers"), HttpHandlersSection)
        Dim handlerExists As Boolean = False
        Dim handlerName As String = handlerType.ToString
        Dim handlerFullName As String = handlerType.AssemblyQualifiedName

        For Each handlerAction As HttpHandlerAction In handlerSection.Handlers
            If handlerAction.Type = handlerName OrElse handlerAction.Type = handlerFullName Then
                handlerExists = True
                hadlerPath = If(handlerAction.Path.StartsWith("~"), String.Empty, String.Format("~/{0}", handlerAction.Path))
                Exit For
            End If
        Next

        If Not handlerExists Then
            Throw New ApplicationException(String.Format(My.Resources.ErrorHandlerNotRegistered, handlerName))
        End If

        Return hadlerPath
    End Function

    Friend Shared Sub DrawCorner(ByVal corner As Options.Corners, ByVal cornerType As Options.CornerTypes, ByRef canvas As Graphics, ByVal fillColor As Color, ByVal imageWidth As Integer, ByVal imageHeight As Integer, ByVal radius As Integer, Optional ByVal border As Pen = Nothing)
        Dim gp As New GraphicsPath
        Dim bgp As New GraphicsPath
        Dim sb As New SolidBrush(fillColor)
        Dim r1 As Integer = radius
        Dim r2 As Integer = radius * 2

        Dim bh1 As Integer = 0
        Dim bh2 As Integer = 0
        If border IsNot Nothing Then
            bh1 = CInt(border.Width / 2)
            bh2 = bh1 * 2
        End If

        Select Case corner
            Case Options.Corners.TopLeft
                Select Case cornerType
                    Case Options.CornerTypes.Round
                        'Corner.
                        gp.AddRectangle(New Rectangle(0, 0, r1 + bh1, r1 + bh1))
                        gp.AddPie(New Rectangle(0, 0, r2 + bh2, r2 + bh2), 180, 90)
                        'Border.
                        If border IsNot Nothing Then
                            bgp.AddArc(New Rectangle(bh1, bh1, r2, r2), 180, 90)
                        End If
                    Case Options.CornerTypes.Strait
                        'Corner.
                        gp.AddPolygon(New Point() {New Point(0, 0), New Point(r1, 0), New Point(0, r1)})
                        'Border.
                        If border IsNot Nothing Then
                            bgp.AddLine(0, r1, r1, 0)
                        End If
                End Select
            Case Options.Corners.TopRight
                Select Case cornerType
                    Case Options.CornerTypes.Round
                        gp.AddRectangle(New Rectangle(imageWidth - r1 - bh1, 0, r1 + bh1, r1 + bh1))
                        gp.AddPie(New Rectangle(imageWidth - r2 - bh2, 0, r2 + bh2, r2 + bh2), 270, 90)
                        If border IsNot Nothing Then
                            bgp.AddArc(New Rectangle(imageWidth - r2 - bh1, bh1, r2, r2), 270, 90)
                        End If
                    Case Options.CornerTypes.Strait
                        gp.AddPolygon(New Point() {New Point(imageWidth, 0), New Point(imageWidth - r1, 0), New Point(imageWidth, r1)})
                        If border IsNot Nothing Then
                            bgp.AddLine(imageWidth - r1 - bh1, 0, imageWidth, r1 + bh1)
                        End If
                End Select
            Case Options.Corners.BottomRight
                Select Case cornerType
                    Case Options.CornerTypes.Round
                        gp.AddRectangle(New Rectangle(imageWidth - r1 - bh1, imageHeight - r1 - bh1, r1 + bh1, r1 + bh1))
                        gp.AddPie(New Rectangle(imageWidth - r2 - bh2, imageHeight - r2 - bh2, r2 + bh2, r2 + bh2), 0, 90)
                        If border IsNot Nothing Then
                            bgp.AddArc(New Rectangle(imageWidth - r2 - bh1, imageHeight - r2 - bh1, r2, r2), 0, 90)
                        End If
                    Case Options.CornerTypes.Strait
                        gp.AddPolygon(New Point() {New Point(imageWidth, imageHeight), New Point(imageWidth, imageHeight - r1), New Point(imageWidth - r1, imageHeight)})
                        If border IsNot Nothing Then
                            bgp.AddLine(imageWidth, imageHeight - r1, imageWidth - r1, imageHeight)
                        End If
                End Select
            Case Options.Corners.BottomLeft
                Select Case cornerType
                    Case Options.CornerTypes.Round
                        gp.AddRectangle(New Rectangle(0, imageHeight - r1 - bh1, r1 + bh1, r1 + bh1))
                        gp.AddPie(New Rectangle(0, imageHeight - r2 - bh2, r2 + bh2, r2 + bh2), 90, 90)
                        If border IsNot Nothing Then
                            bgp.AddArc(New Rectangle(bh1, imageHeight - r2 - bh1, r2, r2), 90, 90)
                        End If
                    Case Options.CornerTypes.Strait
                        gp.AddPolygon(New Point() {New Point(0, imageHeight), New Point(0, imageHeight - r1), New Point(r1, imageHeight)})
                        If border IsNot Nothing Then
                            bgp.AddLine(0, imageHeight - r1 - bh1, r1 + bh1, imageHeight)
                        End If
                End Select
        End Select

        canvas.FillPath(sb, gp)
        If border IsNot Nothing Then canvas.DrawPath(border, bgp)
        gp.Dispose()
        sb.Dispose()
    End Sub

    Friend Shared Function GetImageFilter(ByVal filter As Options.ImageFilters) As ImageAttributes
        Dim ia As New ImageAttributes
        Select Case filter
            Case Options.ImageFilters.BlackAndWhite
                ia = Nothing
            Case Options.ImageFilters.GrayScale
                Dim m As New ColorMatrix(New Single()() _
                {New Single() {0.5, 0.5, 0.5, 0, 0}, _
                 New Single() {0.5, 0.5, 0.5, 0, 0}, _
                 New Single() {0.5, 0.5, 0.5, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})
                ia.SetColorMatrix(m)
            Case Options.ImageFilters.SephiaTone
                Dim m As New ColorMatrix(New Single()() _
                {New Single() {0.393F, 0.349F, 0.272F, 0, 0}, _
                 New Single() {0.769F, 0.686F, 0.534F, 0, 0}, _
                 New Single() {0.189F, 0.168F, 0.131F, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})
                ia.SetColorMatrix(m)
            Case Options.ImageFilters.Negative
                Dim m As New ColorMatrix(New Single()() _
                {New Single() {-1, 0, 0, 0, 0}, _
                 New Single() {0, -1, 0, 0, 0}, _
                 New Single() {0, 0, -1, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})
                ia.SetColorMatrix(m)
            Case Else
                ia = Nothing
        End Select
        Return ia
    End Function

    Friend Shared Sub ConvertToBlackAndWhite(ByRef bmp As System.Drawing.Bitmap)
        Dim x As Integer
        Dim y As Integer
        Dim tolerance As Single = 0
        If tolerance > 1 Or tolerance < -1 Then
            Throw New ArgumentOutOfRangeException
            Exit Sub
        End If
        For x = 0 To bmp.Width - 1 Step 1
            For y = 0 To bmp.Height - 1 Step 1
                Dim clr As Color = bmp.GetPixel(x, y)
                If clr.GetBrightness > 0.5 - (tolerance / 2) Then
                    bmp.SetPixel(x, y, Color.White)
                Else
                    bmp.SetPixel(x, y, Color.Black)
                End If
            Next
        Next
    End Sub

    Friend Shared Function GetImageFromUrl(ByVal url As String) As Drawing.Image
        Dim client As New WebClient
        Try
            Dim imageStream As New MemoryStream(client.DownloadData(url))
            Return Drawing.Image.FromStream(imageStream)
        Catch ex As Exception
        Finally
            client.Dispose()
        End Try
        Return Nothing
    End Function

End Class
